package com.dongdong.service.impl;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.dongdong.api.SeckillApi;
import com.dongdong.mapper.TbSeckillOrderMapper;
import com.dongdong.model.TbSeckillOrder;
import com.dongdong.service.SeckillOrderService;
import com.dongdong.utils.IdWorker;
import com.dongdong.utils.JwtUtil;
import com.dongdong.utils.Result;
import com.dongdong.utils.ResultEnum;
import com.dongdong.vo.SeckillGoodsVO;
import com.dongdong.vo.SeckillOrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SeckillOrderServiceImpl implements SeckillOrderService {
    @Autowired
    private TbSeckillOrderMapper seckillOrderMapper;

    @Autowired
    private SeckillApi seckillApi;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private IdWorker idWorker;

    @Override
    public Result addSeckillOrder(Long id, String accessToken) {

        String userId = jwtUtil.parseJwt(accessToken).getId();

        SeckillGoodsVO vo = (SeckillGoodsVO) redisTemplate.boundHashOps("dongdongshop:seckill").get(id);

//        判断是否存在，不存在秒杀结束
        if (vo == null) {
            return Result.DATA(ResultEnum.SKILL_END);
        }
//        判断时间
        long now = new Date().getTime();
        long end = vo.getEndTime().getTime();
        if ((end - now) <= 0) {
            return Result.DATA(ResultEnum.SKILL_END);
        }
//        判断库存
        if (vo.getStockCount()<=0){
            return Result.DATA(ResultEnum.SKILL_NOT );
        }
//        更新redis
        vo.setStockCount(vo.getStockCount()-1);
        redisTemplate.boundHashOps("dongdongshop:seckill").put(id,vo);


//        更新数据库
        if (vo.getStockCount() == 0){
            seckillApi.updateSeckillGoodsVO(vo);
        }

//        增加订单
        SeckillOrderVO seckillOrderVO = new SeckillOrderVO();
        seckillOrderVO.setId(idWorker.nextId());
        seckillOrderVO.setSeckillId(id);
        seckillOrderVO.setMoney(vo.getCostPrice());
        seckillOrderVO.setSellerId(vo.getSellerId());
        seckillOrderVO.setUserId(userId);
        seckillOrderVO.setCreateTime(new Date());
        seckillOrderVO.setStatus("1");
        TbSeckillOrder order = new TbSeckillOrder();
        BeanUtils.copyProperties(seckillOrderVO,order);
        seckillOrderMapper.insertSelective(order);
        return Result.DATA(ResultEnum.SKILL_SUCCESS);
    }
}
